﻿using UnityEngine;
using System.Collections;

public class PrefabInstantiator : MonoBehaviour {
	
	public int random;
	public GameObject[] prefabs;
	public GameObject mainCamera; 
	public bool instantiated = false;
	public GameObject next;
	public int distance;
	// Use this for initialization
	void Start () {
	}
	
	// Update is called once per frame
	void Update () {
		if(!instantiated && (mainCamera.transform.position.x > this.transform.position.x))
		{
			instantiatePrefab();
		}
		else if((mainCamera.transform.position.x - this.transform.position.x) > distance)
		{
			destroyPrefab();
		}
				//Debug.Log(transform.position.x);
	}
	
	void instantiatePrefab(){
	
		random = Random.Range(0, prefabs.Length - 1);

		next = GameObject.Instantiate(prefabs[random], new Vector3(transform.position.x + distance, transform.position.y, transform.position.z), transform.rotation) as GameObject;
		next.GetComponent<PrefabInstantiator>().mainCamera = mainCamera;
		next.GetComponent<PrefabInstantiator>().distance = distance;
		//next.GetComponent<PrefabInstantiator>().prefabs = prefabs;
		instantiated = true;

	}
	
	void destroyPrefab(){
		Destroy(this.gameObject);
	}
		
		
}
